package com.dongecloud.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    /**
     * http://provider/hello 调用失败时 服务降级 将使用到 fallbackMethod 的方法
     * @return
     */
    @HystrixCommand(fallbackMethod = "error")
    public String hello(){
        int i = 1/0;
        return restTemplate.getForObject("http://provider/hello",String.class);
    }

    /**
     * 注解方式使用异步调用
     * @return
     */
    @HystrixCommand(fallbackMethod = "error")
    public Future<String> hello1(){
        return new AsyncResult<String>() {
            @Override
            public String invoke() {
                return restTemplate.getForObject("http://provider/hello",String.class);
            }
        };
    }

    public String error(Throwable t){
        return "error" + t.getMessage();
    }
}
